package com.zcy.entity;

import java.io.Serializable;
import java.util.Date;

import javax.annotation.PreDestroy;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.zcy.exception.ModelException;
import com.zcy.util.IdGenerate;

/**
 * 基础实体类型
 * @author join
 * 
 */
@MappedSuperclass
public class BaseEntity implements IEntity {
	
	private final static Integer nodeid = 1;//Integer.parseInt(System.getProperty("node"));

	private static final long serialVersionUID = 1L;
	
	private static IdGenerate idGenerate;
	static{
		
		if(nodeid != null){
			idGenerate = new IdGenerate(nodeid, 123);
		}else{
			idGenerate = new IdGenerate(1, 123);	
		}
	}
	
	@Id
	@Column(name="id",length=50)
	@JsonSerialize(using=ToStringSerializer.class)
	private Long id;

	/**
	 * 对象创建时间
	 */
	@Column(name="CREATEDATE")
	@Temporal(TemporalType.TIMESTAMP)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	private Date createDateTime;

	/**
	 * 对象最后修改时间 <br />
	 */
	@Column(name="LASTMODIFY")
	@Temporal(TemporalType.TIMESTAMP)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	private Date lastModifyDateTime;
	
	/**
	 * 对象状态（0:不启用；1:启用） <br />
	 */
	@Column(name="status",length=1)
	private int status = 1;
	

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getLastModifyDateTime() {
		return lastModifyDateTime;
	}

	public void setLastModifyDateTime(Date lastModifyDateTime) {
		this.lastModifyDateTime = lastModifyDateTime;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	/**
	 * 保存或修改对象时触发，用于修改一些通用记录行属性 <br />
	 * eg：lastModifyDateTime（最后修改时间） <br />
	 * @throws ModelException 可通过此方法来控制一些过程中业务数据异常（建议不要随意使用可使用 JSR 303 - Bean Validation 实现）<br />
	 */
	private void preUpdateOrSave() throws ModelException {
		if(this.id == null || this.id == 0){
			this.id = idGenerate.nextId();
			this.createDateTime = new Date();
		}
		this.lastModifyDateTime = new Date();
	}
	
	
	@PrePersist
	public void prePersist() throws ModelException{
		preUpdateOrSave();
	}
	
	@PreUpdate
	public void preUpdate() throws ModelException{
		preUpdateOrSave();
	}
	
	@PreDestroy
	public void preDestroy() throws ModelException{
		
	}
	
}
